package com.zzh.test1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition 实现唤醒线程 阻塞线程
 */
public class Test3 {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        Thread t1 = new Thread(() -> {
            lock.lock();// 必须要持有锁才能调用wait方法 否则会抛出IllegalMonitorStateException异常
            try {
                System.out.println("t1 is waiting");
                condition.await();//阻塞线程
                System.out.println("t1 is waken up");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                lock.unlock();
            }
        }, "t1");
        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


        Thread t2 = new Thread(() -> {
            lock.lock();//必须要持有锁才能调用notify方法 否则会抛出IllegalMonitorStateException异常
            try{
                condition.signal();//唤醒t1线程
                System.out.println("t2 is notifying t1");
            }catch (IllegalMonitorStateException e){
                throw new RuntimeException(e);
            }finally {
                lock.unlock();
            }
        });
        t2.start();

        //输出结果：
        //t2 is notifying t1
        //t1 is waken up

    }
}
